﻿namespace YWM.Common
{
    #region 16位CRC校验
    public static class CRCUtil
    {
        /// <summary>
        /// 检查字节数组的CRC校验是否正确
        /// </summary>
        /// <param name="data">校验数据，字节数组</param>
        /// <returns></returns>
        public static bool CheckCRC16(byte[] data)
        {
            byte[] crc = CRC16(data, data.Length - 2);
            return crc[0] == data[data.Length - 2] && crc[1] == data[data.Length - 1];
        }

        /// <summary>
        /// CRC校验，参数data为字节数组
        /// </summary>
        /// <param name="data">校验数据，字节数组</param>
        /// <param name="length">要校验的字节长度</param>
        /// <returns>字节0是高8位，字节1是低8位</returns>
        public static byte[] CRC16(byte[] data, int length)
        {
            //crc计算赋初始值
            int crc = 0xffff;
            for (int i = 0; i < length; i++)
            {
                crc = crc ^ data[i];
                for (int j = 0; j < 8; j++)
                {
                    int temp;
                    temp = crc & 1;
                    crc = crc >> 1;
                    crc = crc & 0x7fff;
                    if (temp == 1)
                    {
                        crc = crc ^ 0xa001;
                    }
                    crc = crc & 0xffff;
                }
            }
            //CRC寄存器的高低位进行互换
            byte[] crc16 = new byte[2];
            //CRC寄存器的高8位变成低8位，
            crc16[1] = (byte)(crc >> 8 & 0xff);
            //CRC寄存器的低8位变成高8位
            crc16[0] = (byte)(crc & 0xff);
            return crc16;
        }
    }
    #endregion
}
